/**
 * 对象池的简单实现
 * @export
 */
export default class Pool {
  constructor() {
    this.pool = {}
  }

  /**
   * 根据对象标识符
   * 获取对应的对象池
   */
  getPoolBySign(name) {
    return this.pool[name] || (this.pool[name] = [])
  }

  /**
   * 根据传入的对象标识符，查询对象池
   * 对象池为空创建新的类，否则从对象池中取
   */
  getItemByClass(name, className, ...args) {
    let pool = this.getPoolBySign(name)

    let result = (pool.length
      ? pool.shift()
      : new className(...args)
    )

    console.log(`Pool: ${name} - ${pool.length} items remaining, ${pool.length > 0 ? 'got instance' : 'created new'}`);
    return result
  }

  /**
   * 将对象回收到对象池
   * 方便后续继续使用
   */
  recover(name, instance) {
    if (!instance) {
      console.warn('Attempting to recover null instance to pool:', name);
      return;
    }
    
    const pool = this.getPoolBySign(name);
    pool.push(instance);
    console.log(`Pool: ${name} - Recovered instance, now ${pool.length} items`);
  }
}